###
# Author: Samir Nasher Taher
# License: AGPLv3,  for the license text see ../LICENSE
# Description: Test which measures the time for 64 byte pings.
###

from modules import CONFIG
from modules.Test import Test

import subprocess
import re

class Test_ping(Test):
    def getResults(self):
        # There is a "pythonping" package, however it requires root
        pingCmd = [
            'ping',
            self.host,
            '-4',
            '-c', '1',
        ]
        results = []
        for x in range(CONFIG.MEASUREMENTS):
            out = subprocess.run(pingCmd, stdout=subprocess.PIPE)
            results.append(Test_ping.getTime(str(out)))
        return results

    def getTime(out):
        allTimes = re.findall('(?<=avg\/max\/mdev = ).+?(?= ms)', out) # only one match, eg: 5.650/5.650/5.650/0.000
        if len(allTimes) != 0:
            allTimes = allTimes[0].split('/')
            # error detection
            if not allTimes[0] == allTimes[1] == allTimes[2] and allTimes[3] == 0.0:
                raise Error("Something went wrong: " + out)
            return float(allTimes[0])
        else:
            print("Something went wrong, no matches for output:")
            print(out)
            print("Using 0ms for dropped package.")
            return 0

    def getName(self):
       return "64 (56+8) byte pings"
